export default class ShortCut {
    el = document.body;
    datas = [];

    constructor (options) {
        
        if (options){
            this.el.addEventListener('keydown', (e) => {
 
                if (options.preventDefault){
                    e.preventDefault();
                }

                const key = this.parse(e);
                this.datas.forEach(data => {
                    const [_key, handler] = data;

                    if (key === _key) {
                        handler();
                    }
                });
            });
        }
    }

    add(_key, handler) {
        this.datas.push([_key, handler]);
    }

    remove(key, handler) {
        let index = this.datas.findIndex( el => { 

            const [_key, _handler] = el;
            return _key === key  && _handler === handler;
        })

        if (index !== -1) {
            this.datas.splice(index,1)
        }
    }

    parse(e) {
        let shortcut = [];

        if (e.ctrlKey) {
            shortcut.push('ctrl');
        } 

        if (e.altKey) {
            shortcut.push('alt');
        } 
        
        shortcut.push(e.key);

        return shortcut.join('+');
    }
}